from fastapi import APIRouter, Path, status
from sqlalchemy import delete, select, update

from schemas.base import R
from core.database import getDB
from core.exceptions import NormalException
from schemas.client import ClientOption, MqttClientInSchema, MqttClientOutSchema, MqttClientUpdateSchema
from models.client import MqttClientTable


router = APIRouter(prefix="/client", tags=["客户端管理接口"])


@router.post(
    "/{clientType}/",
    summary="创建北向客户端"
)
def createClient(
    data: MqttClientInSchema,
    clientType: ClientOption = Path(
        description="客户端可选类型 MQTT HTTP WebSocket"
    )
):
    with getDB() as db:
        if clientType == ClientOption.MQTT:
            cliExist = db.scalars(select(MqttClientTable).where(MqttClientTable.name == data.name)).one_or_none()
            if cliExist:
                raise NormalException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"客户端<{data.name}>已存在，请勿重复创建"
                )
            db.add(MqttClientTable(**data.model_dump()))
        db.commit()
    return R()


@router.get(
    "/",
    summary="获取客户端详情",
    response_model=R[MqttClientOutSchema]
)
def getClientDetail(name: str):
    with getDB() as db:
        mqttClient = db.scalars(select(MqttClientTable).where(MqttClientTable.name == name)).one_or_none()
        if not mqttClient:
            raise NormalException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="客户端不存在"
            )
    return R(data=MqttClientOutSchema(**mqttClient.dict()))


@router.get(
    "/list/",
    summary="获取客户端列表",
    response_model=R[list[MqttClientOutSchema]]
)
def getClientList():
    result = []
    with getDB() as db:
        mqttClients = db.scalars(select(MqttClientTable)).fetchall()
        result = [MqttClientOutSchema(**cli.dict()) for cli in mqttClients]
    return R(data=result)


@router.put(
    "/",
    summary="修改客户端参数",
    response_model=R
)
def updateClient(name: str, data: MqttClientUpdateSchema):
    with getDB() as db:
        print(name, data)
        db.execute(update(MqttClientTable).where(
            MqttClientTable.name == name
        ).values(**data.model_dump(exclude_none=True)))
        db.commit()
    return R()


@router.delete(
    "/",
    summary="删除指定客户端",
    response_model=R
)
def deleteClient(name: str):
    with getDB() as db:
        db.execute(delete(MqttClientTable).where(MqttClientTable.name == name))
        db.commit()
    return R()
